#!/bin/sh
#
# make changes to man page source after migration from man3 to man3i
#

tmp=/var/tmp/$$
trap "rm -f $tmp.*; exit 0" 0 1 2 3 15

_usage()
{
    echo "Usage: fix-3i [-v] file [...]"
    exit 1
}

verbose=false
while getopts "v?" c
do
    case $c
    in
	v)
	    verbose=true
	    ;;
	?)
	    _usage
	    ;;
    esac
done
shift `expr $OPTIND - 1`

for file
do
    if [ ! -f $file ]
    then
	echo "Error: $file: file not found"
	continue
    fi

    if grep '^\.SH CAVEAT' $file >/dev/null
    then
	awk <$file >$tmp.tmp '
$1 == ".SH" && $2 == "CAVEAT"	{ skip = 1; next }
skip == 1 && $1 == ".SH"	{ skip = 0 }
skip == 0			{ print }'
    else
	cp $file $tmp.tmp
    fi

    sed <$tmp.tmp >$tmp.check \
	-e '/^\.SH DESCRIPTION/i\
.SH CAVEAT\
This documentation is intended for internal Performance Co-Pilot\
(PCP) developer use.\
.PP\
These interfaces are not part of the PCP APIs that are guaranteed to\
remain fixed across releases, and they may not work, or may provide\
different semantics at some point in the future.' \
    # end

    if diff $file $tmp.check >/dev/null
    then
	$verbose && echo "$file: .SH CAVEAT OK"
    else
	mv $tmp.check $file
	echo "$file: .SH CAVEAT added or updated"
    fi

    if grep '#include .*libpcp.h' $file >/dev/null
    then
	$verbose && echo "$file: libpcp.h already in place"
    else
	if grep '#include .*pmapi.h' $file >/dev/null
	then
	    sed <$file >$tmp.tmp \
		-e '/#include .*pmapi.h/{
p
s/pmapi.h/libpcp.h/
i\
.br
}'
	    if diff $file $tmp.tmp >/dev/null
	    then
		$verbose && echo "Botch: $file: failed to add libpcp.h after pmapi.h"
	    else
		echo "$file: add libpcp.h after pmapi.h"
		mv $tmp.tmp $file
	    fi
	else
	    echo "Warning: $file: no place to add libpcp.h"
	fi
    fi

    # and now impl.h is empty, cull include impl.h and preceding .br
    #
    line=`sed <$file -n -e '/include.*impl.h[">]/{
=
q
}'`
    if [ -n "$line" ]
    then
	$verbose && echo "$file: cull impl.h @ line $line"
	rm -f $tmp.err
	awk <$file >$tmp.tmp '
NR == ('$line'-1)	{ if ($0 ~ /^\.br$/) next
			  print "no .br at line",'$line'-1 >>"'$tmp.err'"
			  next
			}
NR == '$line' 		{ next }
			{ print }'
	if [ -s $tmp.err ]
	then
	    echo "Error: $fail: `cat $tmp.err`"
	else
	    mv $tmp.tmp $file
	fi
    fi

    # change #include <pcp/anything.h> to #include "anything.h"
    #
    sed <$file >$tmp.tmp \
	-e '/#include/{
s/<pcp\//"/
s/>/"/
}'
    if diff $file $tmp.tmp >/dev/null
    then
	$verbose && echo "$file: #includes all OK"
    else
	echo "$file: change #includes"
	mv $tmp.tmp $file
    fi

done

exit

